package com.lyz.myself.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyz.myself.config.utils.Result;
import com.lyz.myself.config.utils.base.CodeMsg;
import com.lyz.myself.config.wx.UserConstantInterface;
import com.lyz.myself.config.wx.XcxUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: myself
 * @Date: 2019/2/21 15:27
 * @Author: lyz
 * @Description:
 */
@RestController
@RequestMapping("/api")
public class UserApi {

    /**
     * 登录接口
     *
     * @param encryptedData
     * @param iv
     * @param code
     * @return
     */
    @PostMapping("/onLogin")
    public Result login(String encryptedData, String iv, String code) {
        if (!StringUtils.isNotBlank(code)) {
            return Result.error(CodeMsg.ERROR, "未获取到用户凭证code");
        }
        JSONObject jsonObject = null;
        jsonObject = XcxUtils.getSessionKeyOropenid(code);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        if (StringUtils.isNotBlank(openid) && StringUtils.isNotBlank(sessionKey)) {
            //解密获取用户信息

            JSONObject user=XcxUtils.getUserInfo(encryptedData,sessionKey,iv);
            System.out.println(user);
            return Result.success(user,"成功");
        } else {
            return Result.error(CodeMsg.ERROR, "未获取到用户openid 或 session");
        }
    }
}
